<template>
  <div class="login">
    <div class="login__box">
      <div class="title">宠物便捷服务管理</div>
      <el-form ref="form" :model="formData" :rules="formRules">
        <el-form-item prop="userName">
          <el-input v-model="formData.username" placeholder="用户名" @keyup.native.enter="login" :disabled="formDisabled"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="formData.password" type="password" show-password placeholder="密码" @keyup.native.enter="login" :disabled="formDisabled"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login" :loading="loginLoading">登录</el-button>
        </el-form-item>
      </el-form>
    </div>

  </div>
</template>


<script>
import { allRoutes } from '@/utils/menu'
import { all_routes, error_routes } from '@/router/routes'
import { loginApi } from '@/api/modules/admin'
export default {
  name: 'Login',
  data () {
    return {
      formData: {
        // userName: 'j2',
        // password: 'j2'
        // userName: 'j3',
        // password: 'j3'
        username: 'admin',
        password: '123456'
        // userName: 'admin',
        // password: '123456'
        // userName: null,
        // password: null
      },
      formRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: ['change', 'blur'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: ['change', 'blur'] }
        ]

      },

      formDisabled: false,
      loginLoading: false
    }
  },
  methods: {
    login () {
          if(!this.loginLoading) {

            this.$refs['form'].validate(async valid => {
              if(valid) {
                try {
                  this.formDisabled = true
                  this.loginLoading = true
                  const params = {
                    ...this.formData
                  }
                  const res = await loginApi(params)
                  const accessToken = res.data
                  // const { menuList } = data  // TODO: 暂时不支持动态设置，先用allRoutes进行路由配置
                  const menuList = allRoutes

                  sessionStorage.setItem('Authorization', accessToken)
                  // sessionStorage.setItem('refresh_token', refresh_token)
                  sessionStorage.setItem('MENU_LIST', JSON.stringify(menuList))

                  /* 设置可用路由 */
                  this.setRoutes(menuList)

                  /* 初始界面处理（确保缺省访问的是第一菜单） */
                  const HomeRoute = menuList.find(item => item.name == '首页')
                  if((HomeRoute ?? '') !== '') {
                    this.$router.push({ name: HomeRoute.routeUrl })
                  } else if (menuList.length >= 2) {
                    this.$router.push({ name: menuList[0].routeUrl })
                  } else {
                    this.$router.push({ name: 'Main' })
                  }
                } catch (err) {
                  console.error(err)
                }

                this.formDisabled = false
                this.loginLoading = false
              }
            })
          }



        },
        // 动态添加路由
        setRoutes(menuList) {
          if((menuList ?? '') !== '' && menuList.length !== 0) {
            const routeUrlList = menuList.map(item => item.routeUrl)

            const routes = all_routes.filter(item => {
              return routeUrlList.includes(item.name)
            })

            console.log(routes)

            routes.forEach(route => {
              this.$router.addRoute('Main', route)
            })
            error_routes.forEach(route => {
              this.$router.addRoute(route)
            })
            console.log('所有已配置路由', this.$router.getRoutes())

          } else {
            console.warn('此用户没有菜单')
          }


        }
  }
}
</script>

<style lang="less" scoped>
.login {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  .login__box {
    width: 460px;
    box-sizing: border-box;
    box-shadow: 0 0 25px #CCC;
    padding: 24px;
    .title {
      margin-bottom: 24px;
      text-align: center;
      font-size: 24px;
    }
    .el-button {
      width: 100%;
    }
  }
}
</style>
